<?php

namespace core;

use PDO;
use Exception;

class DB
{
    public static $operater;
    public $table;
    public $pdo;
    public $conf;

    public function __construct($conf)
    {
        $this->conf = $conf;

        try {
            switch ($this->conf['driver']) {
                case "sqlite":
                    $this->pdo  = new PDO("{$conf['driver']}:{$conf['database']}");
                    break;
                case "mysql":
                    $this->pdo  = new PDO("mysql:host={$conf['host']};port={$conf['port']};dbname={$conf['database']}", $conf['username'], $conf['password']);
                    $this->pdo->query("set names {$conf['charset']}");
                    $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                    $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    break;
                default:
                    throw new Exception('不支持的数据库驱动');
            }
        } catch (Exception $e) {
            throw new Exception('数据库连接失败, 请检查数据库相关配置');
        }
    }

    /**
     * 单例模式
     */
    public static function getInstance($conf, $table, $configName)
    {
        if (!isset(self::$operater[$configName])) {
            self::$operater[$configName] = (new db($conf))->pdo;
            self::$operater[$configName]->table = $table;
            return self::$operater[$configName];
        }
        if (self::$operater[$configName]->table == $table) {
            return self::$operater[$configName];
        }
        $cloner = clone self::$operater[$configName];
        $cloner->table = $table;
        return $cloner;
    }
}